import { storage } from "@/utils/storage"
import axios, {
  AxiosError,
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
  type InternalAxiosRequestConfig
} from "axios"
import { ElMessage } from "element-plus"

const prefix = import.meta.env.VITE_BASE_PREFIX
const service = axios.create({
  baseURL: prefix,
  timeout: 5000,
  withCredentials: true
})

class Service {
  public axiosInstance: AxiosInstance
  constructor(axiosInstance: AxiosInstance) {
    this.axiosInstance = axiosInstance

    this.axiosInstance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        if (!config.url?.startsWith("/login")) {
          config.headers["Authorization"] =
            "Bearer " + storage.get("token") || ""
        }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    this.axiosInstance.interceptors.response.use(
      (response: AxiosResponse) => {
        return response.data.data
      },
      (error: AxiosError) => {
        if (error.response?.status === 401) {
          return ElMessage.error("token过期,请重新登录")
        }
        return Promise.reject(error)
      }
    )
  }

  public request<T>(config: InternalAxiosRequestConfig): Promise<T> {
    return this.axiosInstance.request(config)
  }

  public get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.axiosInstance.get(url, config)
  }

  public post<T>(
    url: string,
    data?: unknown,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.axiosInstance.post(url, data, config)
  }

  public put<T>(
    url: string,
    data?: unknown,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.axiosInstance.put(url, data, config)
  }

  public delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.axiosInstance.delete(url, config)
  }
}

export default new Service(service)
